//
//  OAuthViewController.swift
//  weibo
//
//  Created by 陈伟 on 15/10/16.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        
        view = webView
        webView.delegate = self
        //        webView.backgroundColor = UIColor.orangeColor()
        title = "登录微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancellLogin")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoLogin")
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }
}

//web的代理方法
extension OAuthViewController: UIWebViewDelegate {
    
    //将要加载请求的方法
    // 如果 iOS 的代理方法中有返回 bool，通常返回 true 很正常，返回 false 不能正常工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //不包含百度 继续找
        guard let url = request.URL where url.host == "www.baidu.com" else {
            
            return true
        }
        
        //包含 前缀为 “code=”
//        url.query?.hasPrefix(<#T##prefix: String##String#>)
        //此处已包含百度， 查看url.query 中是否包含“code=”取消授权主机也为百度， 所有再次过滤
        guard let query = url.query where query.hasPrefix("code=") else {
            return false
        }
        
        //"code="  可以换成“12345同样可以， 为了直观。。
        let code = query.substringFromIndex("code=".endIndex)

//        print("授权码" + code)
//        
//        //获取token值
//        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
//      
//            if error != nil {
//                print("OAuth里error:" + "\(error)")
//                return
//            }
//            
//            //获取令牌
//            print("OAuth里result:" + "\(result)")
//            //拿到令牌后
//            //字典转模型
//            guard let dict = result as? [String: AnyObject] else {
//                print("滚回去检查")
//                return
//            }
//            let account = UserAccount(dict: dict)
//            
////            print(account)
//            self.loadAccount(account)
//            
//        }
        loadAccessToken(code)
        
        //授权不跳转，如果为true会跳转到授权页面（www.baidu.com）
        return false
    }
//    func loadAccount(account: UserAccount) {
//        NetworkTools.sharedTools.loadUserInfo(account.uid!, accessToken: account.access_token!, finished: { (result, error) -> () in
//            if  result == nil {
//                print(error)
//            }else {
//                
//                guard let dict = result as? [String: AnyObject] else {
//                    print("cuowu")
//                    return
//                }
//                
//                account.avatar_large = dict["avatar_large"] as? String
//                account.screen_name = dict["screen_name"] as? String
//                account.saveUserAccount()
//                
//            }
//        })
//    }
    private func loadAccessToken(code: String){
        
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccess) -> () in
            if isSuccess {
                print("成功")
                
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "登录界面发来通知")
                })
                                
            }else{
                print("失败")
            }
        }
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}

extension  OAuthViewController{
    
    @objc private func cancellLogin() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //通过网页来获取此段代码；
    @objc private func autoLogin() {
        
//        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
//        "document.getElementById('passwd').value = 'qqq123';"
        let js = "document.getElementById('userId').value = 'chnvi999@sina.com';" +
        "document.getElementById('passwd').value = '809058';"

        webView.stringByEvaluatingJavaScriptFromString(js)
    }
}
